package com.oocl.batchdata.processor;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Scanner;

import com.oocl.batchdata.pojo.Customer;
import com.oocl.batchdata.service.CustomerService;
import com.oocl.batchdata.util.FormatPrinter;

import static com.oocl.batchdata.util.StringValidator.*;

public class FileProcessor {
	
	private OutputStream out;
	private final int CUSTOMER_INFO_TYPE_COUNT = 5;
	private CustomerService service = CustomerService.INSTANCE;
	
	public FileProcessor(OutputStream out) {
		this.out = out;
	}

	public void processFile(String fileUri) throws FileNotFoundException, NumberFormatException, ParseException {
		Scanner scanner = new Scanner(new FileInputStream(fileUri));
		while (scanner.hasNextLine()) {
			String reader = scanner.nextLine();
			String[] infos = reader.trim().split("[ \t]+");
			
			if (infos.length != CUSTOMER_INFO_TYPE_COUNT) {
				continue;
			}
			
			if (idValidate(infos[0]) && emailValidate(infos[2])
					&& sexValidate(infos[3]) && dateValidate(infos[4])) {
				Customer customer = new Customer(Integer.parseInt(infos[0]),
						infos[1], infos[2], Boolean.parseBoolean(infos[3]),
						new SimpleDateFormat("yyyy-MM-dd").parse(infos[4]));
				service.addCustomer(customer);
			}
		}
		FormatPrinter.printTable(service.getCustomersOrderById(), out);
		FormatPrinter.printTable(service.getCustomersOrderByBirthday(), out);
		FormatPrinter.printXML(service.getCustomersOrderById(), out);
		scanner.close();
	}
}
